package com.org.qrtrace.utils;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QRCodeUtil {

    private static final Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);

    public static String createQRCodeAndReturnBase64(String contents, int width, int height) {

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            contents = new String(contents.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            BitMatrix bitMatrix = qrCodeWriter.encode(contents, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Base64.Encoder encoder = Base64.getEncoder();

        //这里直接加上"data:image/png;base64,",前端不用再次去处理了

        //System.out.println(text);
        String res = encoder.encodeToString(outputStream.toByteArray());
        return "data:image/png;base64,"+res;
    }

}
